import log4js from 'log4js'

log4js.configure({
  // 如果使用pm2集群来多进程输出日志, 需添加下面2个语句
  pm2: true,
  disableClustering: true,

  appenders: {
    file: {
      type: 'dateFile',
      filename: './log/log',
      pattern: 'yyMMdd.log',
      alwaysIncludePattern: true
    },
    console: {
      type: 'stdout'
    },
    error: { // 错误日志
      type: 'dateFile',
      filename: './log/error/err',
      pattern: 'yyMMdd.log',
      backups: 10,
      maxLogSize: 10485760,
      compress: true,
      alwaysIncludePattern: true
    }
  },
  categories: {
    default: { appenders: [ 'file', 'console' ], level: 'debug' },
    error: { appenders: [ 'error', 'console'], level: 'error' }
  }
})

let logFormat = (message, ctx = null, res_time = 0) => {
    let params = {}
    if (ctx) {
        let method = ctx?.method ?? ''
        let url = ctx?.url ?? ''
        let body = ctx.request?.body ?? ''
        let user_agent = ctx.header?.userAgent ?? ''
        const ip = ctx.request.ip ?? ''
        params = { method, url, body, user_agent, ip }
    }
    if (res_time)
        params['res_time'] = res_time
    params['message'] = message
    return params
}

export function ilog(message, ctx = null, res_time = 0) {
  log4js.getLogger().info(logFormat(message, ctx, res_time))
}

export function tlog(message, ctx = null, res_time = 0) {
  log4js.getLogger().debug(logFormat(message, ctx, res_time))
}

export function wlog(message, ctx = null, res_time = 0) {
  log4js.getLogger().warn(logFormat(message, ctx, res_time))
}

export function elog(message, ctx = null) {
  log4js.getLogger('error').error(logFormat(message, ctx))
}
